package com.das.mechanic_base.mapi.response;

import android.app.Activity;
import android.util.Log;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BaseCallModel;
import com.das.mechanic_base.utils.AppSelfException;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.tencent.bugly.crashreport.CrashReport;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.disposables.Disposable;

/**
 * Created by chensi on 2018/3/26.
 */

public abstract class HttpCallBack<T> extends BaseObserver<X3BaseCallModel<T>> {

    private String type;

    protected HttpCallBack() {
    }

    protected HttpCallBack(String type) {
        this.type = type;
    }

    //对应HTTP的状态码
    private final int UNAUTHORIZED = 401;
    private final int FORBIDDEN = 403;
    private final int NOT_FOUND = 404;
    private final int REQUEST_TIMEOUT = 408;
    private final int INTERNAL_SERVER_ERROR = 500;
    private final int BAD_GATEWAY = 502;
    private final int SERVICE_UNAVAILABLE = 503;
    private final int GATEWAY_TIMEOUT = 504;

    private final int LOGIN_TOKEN_ERROR = 1201;
    private final int TOKEN_EXPIRE = 1202;
    private final int ONE_SELF_LOGIN = 320;

    @Override
    public void onComplete() {
        super.onComplete();
        //hideLoading();
    }

    @Override
    public void onSubscribe(Disposable d) {
        super.onSubscribe(d);
        onCancelNet(d);
        if (!"upload".equals(type)) {
            //showLoading();
        }
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        //hideLoading();
        Throwable throwable = e;
        //获取最根源的异常
        while (throwable.getCause() != null) {
            e = throwable;
            throwable = throwable.getCause();
            Log.e("net error",  e.getCause() +"");
        }
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            switch (httpException.code()) {
                case LOGIN_TOKEN_ERROR:
                case TOKEN_EXPIRE:
                case FORBIDDEN:
                case ONE_SELF_LOGIN:
                case UNAUTHORIZED:

                    boolean isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);
                    if (isSdk) {
                        X3MyApp.getInstance().loginSync();
                    }else {
                        if (getContext() != null) {
                            X3ToastUtils.showMessage(getContext().getString(R.string.x3_go_to_login));
                        }
                        SpHelper.saveData("token", "");
                        X3MyApp.getInstance().logout();
                    }

                    break;
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    if (getContext() != null) {
                        X3ToastUtils.showMessage(getContext().getString(R.string.x3_server_http_error));
                    }
                    break;
            }
        } else if (e instanceof SocketTimeoutException) {
            if (getContext() != null) {
                X3ToastUtils.showMessage(getContext().getString(R.string.x3_network_error));
            }

        } else if (e instanceof ConnectException) {
            if (getContext() != null) {
                X3ToastUtils.showMessage(getContext().getString(R.string.x3_server_http_error));
            }
        } else {
            if (getContext() != null) {
                X3ToastUtils.showMessage(getContext().getString(R.string.x3_network_error));
            }
        }
        try {
            String mobile = (String) SpHelper.getData("mobile","0000");
            if(!X3StringUtils.isEmpty(mobile) && mobile.length() > 4){
                mobile = mobile.substring(mobile.length()-4);
            }
            CrashReport.postCatchedException(new AppSelfException( mobile + "-" + e.getCause().getMessage()));
        }catch (Exception ce){}

        NoNetCallBack();
    }

    @Override
    public void onNext(X3BaseCallModel<T> tBaseCallModel) {
        if (tBaseCallModel.status == 0) {
            onDone(tBaseCallModel.data);
            onComplete();
            return;
        } else {
            Object token = SpHelper.getData("token", "");
            if (token != null) {
                X3ToastUtils.showMessage(tBaseCallModel.errorInfo);
            }
            showErrorStatus(tBaseCallModel.status);
            if (1995 != tBaseCallModel.status) {
                showError(tBaseCallModel.errorInfo);
            }
        }
    }

    protected abstract void onDone(T t);

    protected X3BaseActivity getContext() {
        Activity activity = X3MyApp.getInstance().getTopActivity();
        if (activity instanceof X3BaseActivity) {
            return (X3BaseActivity) activity;
        }
        return null;
    }

    @Override
    public void showErrorStatus(int status) {

    }

    protected void showLoading() {
        X3BaseActivity activity = getContext();
        if (activity != null) {
            activity.showLoading(LoadingMessage());
        }
    }

    protected void hideLoading() {
        X3BaseActivity activity = getContext();
        if (activity != null) {
            activity.hideLoading();
        }
    }

    @Override
    protected String LoadingMessage() {
        return null;
    }

    protected abstract void showError(String error);

    // 取消网络请求
    protected void onCancelNet(Disposable disposable) {

    }

    @Override
    protected void NoNetCallBack() {
    }
}

